//
//  GameViewController.swift
//  TetrisGame
//
//  Created by mac on 2020/11/23.
//

import SpriteKit


/// GameViewController
class GameViewController: UIViewController {
    
    var swiftris:Swiftris!
    var panPointReference:CGPoint?
    
    
    //MARK: - override
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = K_APP_VIEWCONTROLLER_BACKGROUND_COLOR
        
        var skView:SKView? = self.view as? SKView
        if skView == nil {
            skView = SKView.init(frame: self.view.bounds)
            self.view.addSubview(skView!)
        }
        
        skView?.showsFPS = true
        skView?.isMultipleTouchEnabled = false
        skView?.presentScene(self.scene)

        swiftris = Swiftris()
        swiftris.delegate = self
        swiftris.beginGame()
        
        //点击事件
        let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(didTap(sender:)))
        tapGesture.delegate = self
        self.view.isUserInteractionEnabled = true
        self.view.addGestureRecognizer(tapGesture)
        
        //平移事件
        let panGesture = UIPanGestureRecognizer.init(target: self, action: #selector(didPan(sender:)))
        panGesture.delegate = self
        self.view.addGestureRecognizer(panGesture)
        
        //轻扫事件
        //let swipteGesture = UISwipeGestureRecognizer.init(target: self, action: #selector(didSwipe(sender:)))
        //swipteGesture.delegate = self
        //self.view.addGestureRecognizer(swipteGesture)
    }
    
    override var prefersStatusBarHidden: Bool {
        return true
    }
    
    
    //MARK: - lazy load
    private lazy var scene:GameScene = {
        autoreleasepool {
            let _gs = GameScene.init(size: self.view.bounds.size)
            _gs.scaleMode = .aspectFill
            _gs.tick = didTick

            return _gs
        }
    }()
}


//MARK: -
extension GameViewController {
    
    func didTick() {
        swiftris.letShapeFall()
        //swiftris.fallingShape?.lowerShapeByOneRow()
        //scene.redrawShape(shape: swiftris.fallingShape!, completion: {})
    }
    
    func nextShape() {
        let newShapes = swiftris.newShape()
        guard let fallingShape = newShapes.fallingShape else {
            return
        }
        
        self.scene.addPreviewShapeToScene(shape: newShapes.nextShape!) {}
        self.scene.movePreviewShape(shape: fallingShape) {
            self.view.isUserInteractionEnabled = true
            self.scene.startTicking()
        }
     }
}


//MARK: - SwiftrisDelegate
extension GameViewController : SwiftrisDelegate {
    
    
    /// 游戏开始后调用
    /// - Parameter swiftris:
    func gameDidBegin(swiftris: Swiftris) {
        
        //levelLabel.text = "\(swiftris.level)"
        //scoreLabel.text = "\(swiftris.score)"
        scene.tickLengthMillis = TickLengthLevelOne
        
        // The following is false when restarting a new game
        if swiftris.nextShape != nil && swiftris.nextShape!.blocks[0].sprite == nil {
            scene.addPreviewShapeToScene(shape: swiftris.nextShape!) { [unowned self] in
                self.nextShape()
            }
        }
        else {
            self.nextShape()
        }
    }

    
    /// 游戏结束(失败)后调用
    /// - Parameter swiftris:
    func gameDidEnd(swiftris: Swiftris) {
        view.isUserInteractionEnabled = false
        scene.stopTicking()
        
        scene.playSound(sound: "gameover.mp3")
        print("游戏挑战失败")
//        scene.animateCollapsingLines(linesToRemove: swiftris.removeAllBlocks(), fallenBlocks: swiftris.removeAllBlocks()) {
//           swiftris.beginGame()
//        }
    }

    func gameDidLevelUp(swiftris: Swiftris) {
         //levelLabel.text = "\(swiftris.level)"
         if scene.tickLengthMillis >= 100 {
             scene.tickLengthMillis -= 100
         }
         else if scene.tickLengthMillis > 50 {
             scene.tickLengthMillis -= 50
         }
         scene.playSound(sound: "levelup.mp3")
    }

    func gameShapeDidDrop(swiftris: Swiftris) {
        scene.stopTicking()
        scene.redrawShape(shape: swiftris.fallingShape!) {
            swiftris.letShapeFall()
        }
        
        scene.playSound(sound: "drop.mp3")
    }

    func gameShapeDidLand(swiftris: Swiftris) {
        scene.stopTicking()
        
        self.view.isUserInteractionEnabled = false

        let removedLines = swiftris.removeCompletedLines()
        if removedLines.linesRemoved.count > 0 {
            //self.scoreLabel.text = "\(swiftris.score)"
            scene.animateCollapsingLines(linesToRemove: removedLines.linesRemoved, fallenBlocks:removedLines.fallenBlocks) {
                self.gameShapeDidLand(swiftris: swiftris)
            }
            scene.playSound(sound: "bomb.mp3")
        }
        else {
            self.nextShape()
        }
    }

    func gameShapeDidMove(swiftris: Swiftris) {
        scene.redrawShape(shape: swiftris.fallingShape!) {}
    }
}


//MARK: - UIGestureRecognizerDelegate
extension GameViewController : UIGestureRecognizerDelegate {
 
    /// 点击事件
    /// - Parameter sender: UITapGestureRecognizer
    @objc func didTap(sender:UITapGestureRecognizer) {
        swiftris.rotateShape()
    }

    
    /// 平移事件
    /// - Parameter sender: UIPanGestureRecognizer
    @objc func didPan(sender:UIPanGestureRecognizer) {
        let currentPoint = sender.translation(in: self.view)
        if let originalPoint = panPointReference {

            if abs(currentPoint.x - originalPoint.x) > (BlockSize * 0.9) {
                if sender.velocity(in: self.view).x > CGFloat(0) {
                    swiftris.moveShapeRight()
                    panPointReference = currentPoint
                } else {
                    swiftris.moveShapeLeft()
                    panPointReference = currentPoint
                }
            }
        } else if sender.state == .began {
            panPointReference = currentPoint
        }
    }
    
    
    /// 轻扫事件
    /// - Parameter sender: UISwipeGestureRecognizer
    @objc func didSwipe(sender:UISwipeGestureRecognizer) {
        swiftris.dropShape()
    }
    
    
    //MARK: -
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        if gestureRecognizer is UISwipeGestureRecognizer {
            if otherGestureRecognizer is UIPanGestureRecognizer {
                return true
            }
        }
        else if gestureRecognizer is UIPanGestureRecognizer {
            if otherGestureRecognizer is UITapGestureRecognizer {
                return true
            }
        }
        return false
    }
}
